package main

import (
	"context"
	"fmt"
	"gim-server/apis/c2c"
	"gim-server/apis/com"
	"gim-server/apis/conversation"
	"gim-server/apis/demo"
	"gim-server/apis/open"
	"gim-server/apis/rtc"
	"gim-server/apis/signaling"
	"gim-server/apis/ws"
	"gim-server/config"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	cfg := config.GetCfg()
	engine := gin.Default()
	c2c.ApiReg(engine)
	com.ApiReg(engine)
	conversation.ApiReg(engine)
	open.ApiReg(engine)
	signaling.ApiReg(engine)
	rtc.ApiReg(engine)
	ws.ApiReg(engine)
	demo.ApiReg(engine)
	engine.Static("/gim/files", cfg.UploadFilePath)
	srv := &http.Server{
		Addr:    fmt.Sprintf(":%v", cfg.ServerPort),
		Handler: engine,
	}
	go func() {
		log.Printf(" - Server Run In http://127.0.0.1:%v\n", cfg.ServerPort)
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()

	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("Shutdown Server ...")
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server Shutdown:", err)
	}
	select {
	case <-ctx.Done():
		log.Println("timeout of one seconds.")
	}
	log.Println("Server exiting")
}
